package com.example.wuqujingdianphone.activity;

import android.app.ProgressDialog;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bifan.txtreaderlib.ui.HwTxtPlayActivity;
import com.example.wuqujingdianphone.R;
import com.example.wuqujingdianphone.base.BaseActivity;
import com.example.wuqujingdianphone.utils.SPUtil;
import com.example.wuqujingdianphone.utils.ToastUtil;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.vise.xsnow.http.ViseHttp;
import com.vise.xsnow.http.callback.ACallback;
import com.vise.xsnow.http.mode.DownProgress;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;

public class BookReadActivity extends BaseActivity implements OnDrawListener, OnLoadCompleteListener, OnPageChangeListener {
    private static final String TAG = "BookReadActivity";
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.title)
    TextView title;

    String pdfurl;
    @BindView(R.id.pdfView)
    PDFView pdfView;

    String fielPath;
    @BindView(R.id.tip)
    TextView tip;
    /*  @BindView(R.id.activity_hwtxtplay_readerView)
      TxtReaderView mTxtReaderView;*/
    private ProgressDialog progressDialog;
    private String fileNmae;

    private int fileType = 0; //1：pdf ;2:txt; 0:格式错误

    private boolean isDestroy;

    private int curPage;
    private int totalPage;
    private File nbFile;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_read);
        ButterKnife.bind(this);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title.setText("阅读");
        progressDialog = new ProgressDialog(this);
        pdfurl = getIntent().getStringExtra("pdfurl");
        Log.i(TAG, "onCreate: pdfurl=" + pdfurl);

        if (!TextUtils.isEmpty(pdfurl)) {
            tip.setVisibility(View.GONE);
            fileNmae = pdfurl;
            if (!TextUtils.isEmpty(fileNmae)) {
                if (fileNmae.contains(".pdf") && !fileNmae.contains("favouriteId")) {
                    Log.i(TAG, "onCreate: pdf格式的文件");
                    fileType = 1;
                    int index = fileNmae.lastIndexOf("/");
                    fileNmae = fileNmae.substring(index + 1, fileNmae.length() - 4);
                    Log.i(TAG, "onCreate: fileNmae=" + fileNmae);

                } else if (fileNmae.contains(".txt") && !fileNmae.contains("favouriteId")) {
                    Log.i(TAG, "onCreate: txt格式的文件");
                    fileType = 2;
                    int index = fileNmae.lastIndexOf("/");
                    fileNmae = fileNmae.substring(index + 1, fileNmae.length() - 4);
                    Log.i(TAG, "onCreate: fileNmae=" + fileNmae);

                } else if (fileNmae.contains(".pdf") && fileNmae.contains("favouriteId")) {
                    Log.i(TAG, "onCreate: pdf格式的文件");
                    fileType = 1;
                    fileNmae = fileNmae.substring(0, fileNmae.indexOf("?"));
                    int index = fileNmae.lastIndexOf("/");
                    fileNmae = fileNmae.substring(index + 1, fileNmae.length() - 4);
                    Log.i(TAG, "onCreate: fileNmae=" + fileNmae);

                } else if (fileNmae.contains(".txt") && fileNmae.contains("favouriteId")) {
                    fileType = 2;
                    fileNmae = fileNmae.substring(0, fileNmae.indexOf("?"));
                    int index = fileNmae.lastIndexOf("/");
                    fileNmae = fileNmae.substring(index + 1, fileNmae.length() - 4);
                } else {
                    fileType = 0;
                    Toast.makeText(this, "文件格式错误", Toast.LENGTH_SHORT).show();
                    return;
                }
            }


            fielPath = "sdcard" + Environment.getExternalStorageDirectory().getPath();
            Log.i(TAG, "onCreate: fielPath=" + fielPath);
            nbFile = new File(fielPath + "/download", fileNmae);
            if (nbFile.exists()) {
                Log.i(TAG, "onCreate: 文件已存在");
                switch (fileType) {
                    case 1:
                        String cP = SPUtil.getString(this, nbFile.getName(), "BookCurPage", String.valueOf(0));
                        int i = Integer.valueOf(cP);
                        openPDFDocument(nbFile, i);
                        break;
                    case 2:
                        loadTxtFile(nbFile.getPath());
                        break;
                    case 0:
                        Log.i(TAG, "onCreate: 这里应该执行不到");
                        Toast.makeText(this, "格式文件错误", Toast.LENGTH_SHORT).show();
                        break;
                }


            } else {
                Log.i(TAG, "onCreate: 还没有改文件去下载 ");

                switch (fileType) {
                    case 1:
                        downPDFFile();
                        break;
                    case 2:
                        downTxtFile();
                        break;
                    case 0:
                        Toast.makeText(this, "格式文件错误,无法下载", Toast.LENGTH_SHORT).show();
                        break;
                }

            }


        } else {
            tip.setVisibility(View.VISIBLE);
        }


    }

    private void downTxtFile() {
        progressDialog.setMessage("加载中...");
        progressDialog.show();
        ViseHttp.DOWNLOAD(pdfurl)
                //.baseUrl(ApiConfig.APP_URL)
                .setFileName(fileNmae)
                .setRootName(fielPath)
                .request(new ACallback<DownProgress>() {
                    @Override
                    public void onSuccess(DownProgress downProgress) {
                        Log.i(TAG, "onSuccess: txt文件下载成功");
                        progressDialog.dismiss();
                        File file = new File(fielPath + "/download", fileNmae);
                        if (file.exists()) {
                            Log.i(TAG, "onSuccess: file is  exists  fielPath= " + file.getPath());
                            loadTxtFile(file.getPath());
                        } else {
                            Log.i(TAG, "onSuccess: file is not exists");
                        }
                    }


                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.i(TAG, "downTxtFile onFail: errCode=" + errCode + " errMsg=" + errMsg);
                        progressDialog.dismiss();
                        if (errCode == 1006) {
                            ToastUtil.show("请求超时");
                        } else {
                            ToastUtil.show("网络请求超时");
                        }


                    }
                });
    }


    private void downPDFFile() {
        showDialog();
        ViseHttp.DOWNLOAD(pdfurl)
                .tag(TAG)
                //.baseUrl(ApiConfig.APP_URL)
                .setFileName(fileNmae)
                .setRootName(fielPath)
                .request(new ACallback<DownProgress>() {
                    @Override
                    public void onSuccess(DownProgress downProgress) {
                        if (!isDestroy) {
                            if (downProgress.getPercent() != null) {
                                String percent = downProgress.getPercent();
                                long bytes_downloaded = downProgress.getDownloadSize();
                                long bytes_total = downProgress.getTotalSize();
                                int progress = (int) ((bytes_downloaded * 100) / bytes_total);

                                progressDialog.setProgress(progress);

                                if (percent != null && percent.equals("100.00%")) {
                                    progressDialog.dismiss();
                                    Toast.makeText(BookReadActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
                                    File file = new File(fielPath + "/download", fileNmae);
                                    if (file.exists()) {
                                        Log.i(TAG, "downPDFFile onSuccess: file is exists");
                                        openPDFDocument(file, 0);
                                    } else {
                                        Log.i(TAG, " downPDFFile onSuccess: file is not exists");
                                    }
                                }
                            }
                        }


                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        Log.i(TAG, "downPDFFile onFail: errCode=" + errCode + " errMsg=" + errMsg);
                    }
                });
    }


    private void openPDFDocument(File file, int curPage) {
        pdfView.fromFile(file)
                //.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default //所有页面默认显示
                .defaultPage(curPage)  ////默认展示第一页
                .enableSwipe(true) // allows to block changing pages using swipe //允许阻止改变页面使用刷卡
                .swipeHorizontal(true)
                .enableDoubletap(true)
                .onDraw(this) // allows to draw something on a provided canvas, above the current
                // page
                .onLoad(this) // called after document is loaded and starts to be rendered
                // 称为文档加载后,开始呈现
                .onPageChange(this)
                //  .onPageScroll(onPageScrollListener)
                //  .onError(onErrorListener)
                // .onRender(onRenderListener) // called after document is rendered for the first time
                // forms)
                // .password(null)
                // .scrollHandle(null)
                //.enableAntialiasing(true) // improve rendering a little bit on low-res screens
//                .pageFitPolicy(FitPolicy.BOTH)
                .spacing(10)
                .pageFling(true)
                .pageSnap(true)
                .swipeHorizontal(true)
                .enableSwipe(true)
                .enableDoubletap(true)
                .enableAntialiasing(true)
                .enableAnnotationRendering(true) // render annotations (such as comments, colors or
                .enableAnnotationRendering(true)
                .load();
        pdfView.jumpTo(10, true);
        // pdfView.setMaxZoom(30);
        //pdfView.zoomTo(2);
    }

    private void loadTxtFile(String FilePath) {
        HwTxtPlayActivity.loadTxtFile(this, FilePath);
        finish();
       /* mTxtReaderView.loadTxtFile(FilePath, new ILoadListener() {
            @Override
            public void onSuccess() {
                //加载成功回调
            }

            @Override
            public void onFail(TxtMsg txtMsg) {
                //加载失败回调
            }

            @Override
            public void onMessage(String message) {
                //加载过程信息回调
            }
        });*/

    }


    public void showDialog() {

        // 设置对话框参数
        progressDialog.setIcon(R.mipmap.ic_launcher);
        //progressDialog.setTitle("软件下载");
        progressDialog.setMessage("下载中...");
        progressDialog.setCancelable(true);
        // 设置进度条参数
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(100);
        // progressDialog.incrementProgressBy(0);
        progressDialog.setIndeterminate(false); // 填false表示是明确显示进度的 填true表示不是明确显示进度的
       /* progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });*/
       /* progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                progressDialog.dismiss();

                finish();
            }
        });*/
        progressDialog.show();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
        isDestroy = true;
        try {
            //ViseHttp.cancelTag(TAG);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

    }

    @Override
    public void loadComplete(int nbPages) {
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        curPage = page;
        totalPage = pageCount;
//        ToastUtil.show(curPage + "/" + totalPage);
        title.setText(curPage + "/" + totalPage);
        //ToastUtils.showShort(this,curPage + "/" + totalPage);
        if (nbFile.exists()) {
            Log.i("ashdjkas", nbFile.getName());
            SPUtil.putString(this, nbFile.getName(), "BookCurPage", String.valueOf(curPage));

        }
    }
}
